import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:wis_flutter/home.dart';
import 'package:wis_flutter/wis_component/notification/notificationEnum.dart';
import 'package:wis_flutter/wis_component/notification/notificationModel.dart';
import 'package:wis_flutter/wis_component/websocket/webSocketData.dart';
import 'package:wis_flutter/wis_component/websocket/webSocketModel.dart';

WebSocketChannel channel;

class WebSocketManager {
  WebSocketModel webSocketModel;

  initWebSocketManager(WebSocketModel model,BuildContext context) {
    webSocketModel=model;
    if (webSocketModel.wsPath != null) {
      //channel = IOWebSocketChannel.connect(webSocketModel.getWebSocketPath(1) );

      if(webSocketModel.userId != null){
        channel = IOWebSocketChannel.connect(webSocketModel.getWebSocketPath(webSocketModel.userId) );
        webSocketModel.setChannel(channel); //方便回调时使用
      }
      webSocketModel=model;
      listenSocket(context);
    }
    return channel;
  }

  void listenSocket(BuildContext context) {
    channel.stream.listen((messageinfo) {
      if (messageinfo != null && messageinfo != "") {
        SocketMessage message = getSocketDefaultMessage(messageinfo);

        if (webSocketModel.bindNotification) {
          //图片 文本、默认
          //如果绑定消息通知

          if (NotificationEnum.BIG_TXT.toString() == message.messageType) {
            notificationManage.createBigTextNotification(NotificationModel(
                id: 2,
                title: message.title,
                body: message.content,
                successNotification: (NotificationModel model) => {
                      if (webSocketModel.callback != null)
                        {webSocketModel.callback(messageinfo)}
                    }));
          } else if (NotificationEnum.IMAGE.toString() == message.messageType) {
            notificationManage.createPictureNotification(NotificationModel(
                id: 3,
                title: message.title,
                body: message.content,
                resourcePath: message.resourcePath,
                successNotification: (NotificationModel model) => {
                      if (webSocketModel.callback != null)
                        {webSocketModel.callback(messageinfo)}
                    }));
          } else {
            //默认消息提醒
            notificationManage.createDefaultNotification(NotificationModel(
                id: 1,
                title: message.title,
                body: message.content,
                successNotification: (NotificationModel model) => {
                      if (webSocketModel.callback != null)
                        {webSocketModel.callback(messageinfo)}
                    }));
          }
        } else {
          showMessage(context, messageinfo);
        }
      }
    }, onError: (messages) {
      showMessage(context, messages);
    });
  }

  SocketMessage getSocketDefaultMessage(String message) {
    WebSocketResult webSocketResult =
        WebSocketResult.fromJson(json.decode(message));
    if (webSocketResult.success) {
      //SocketMessage dataIndex = webSocketResult.getDataIndex(0);
      return SocketMessage.fromJson(webSocketResult.data);
    } else {
      //公共处理
    }
    return null;
  }

  void showMessage(BuildContext context, messageinfo) {
    Future.delayed(Duration(milliseconds: 1), () {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示："),
            content: Text(messageinfo.toString()),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    });
  }

  void sendHandle(messageInfo) {
    print(messageInfo);
    channel.sink.add(messageInfo);
  }

  void dispose() {
    webSocketModel=null;
    channel.sink.close();
  }
}
